package ClassifyService

import (
	"context"
	"gdshop-back-end-go/client-api/app/response/ClassifyResp"
	toolsDb "gdshop-back-end-go/common/db"
	"github.com/gogf/gf/frame/g"
	"strings"
)

func Tree(ctx context.Context) []*ClassifyResp.TreeItem {
	resultList := []*ClassifyResp.TreeItem{}
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "category").Where(
		"type=5").Structs(&resultList)
	if err != nil {
		return nil
	}
	photoUrlProfix := g.Cfg().GetString("site.PhotoUrlProfix")
	mainList := []*ClassifyResp.TreeItem{}
	for _, one := range resultList {
		if one.ParentId == 0 {
			mainList = append(mainList, one)
		}
	}
	for _, main := range mainList {
		//main.Subs = []*ClassifyResp.TreeItem{}
		if len(main.Cover) > 0 && strings.Index(main.Cover, "http") < 0 {
			main.Cover = photoUrlProfix + main.Cover
		}

		for _, sub := range resultList {
			//sub.Subs = []*ClassifyResp.TreeItem{}
			if strings.Index(sub.Cover, "http") < 0 {
				sub.Cover = photoUrlProfix + sub.Cover
			}
			if sub.ParentId == main.Id {
				main.Subs = append(main.Subs, sub)
			}
		}
	}
	return mainList
}
